// pages/goodsDetail/goodsDetail.js
import {
  store
} from '../../store/store'
import {
  storeBindingsBehavior
} from 'mobx-miniprogram-bindings'
const app = getApp()
let flag = 0
Page({
  behaviors: [storeBindingsBehavior],
  storeBindings: {
    store,
    fields: {
      active: 'activeTabbarIndex'
    },
    actions: {
      updateActive: 'updateActiveTabbarIndex'
    }
  },
  data: {
    goods: {}, //商品列表
    cartList: [], //购物车列表
    checkedList: [] //选中列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getGoodsDetail(options.id)
    this.watchValue()
    this.setData({
      cartList: app.globalData.cartList,
      checkedList: app.globalData.checkedList
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    flag = 0
  },
  getGoodsDetail(goods_id) {
    //根据传过来的id来查询商品数据
    wx.cloud.database().collection('goods').doc(goods_id).get()
      .then(res => {
        console.log(res)
        flag += 2
        this.setData({
          goods: res.data
        })
      })
  },
  //添加到购物车
  addCart() {
    let allready = false
    let that = this
    app.globalData.cartList.find(function (value) {
      if (value._id == that.data.goods._id) {
        allready = true
      }
    })
    //添加数据到全局数组
    if (!allready) {
      app.globalData.cartList.push(this.data.goods)
      app.globalData.goodsNumber.push(1)
      app.globalData.checkedList.push(true)
      wx.showToast({
        title: '添加成功',
      })
    } else {
      wx.showToast({
        title: '商品已经存在',
        icon: 'error'
      })
    }
    this.setData({
      cartList: app.globalData.cartList
    })
    wx.setStorageSync('cartList', app.globalData.cartList)
    wx.setStorageSync('goodsNumber', app.globalData.goodsNumber)
    wx.setStorageSync('checkedList', app.globalData.checkedList)
  },
  //跳转到订单页面
  toOrder() {
    let orderList = []
    this.data.goods.need = 1 //所需数量
    orderList.push(this.data.goods) //添加进全局数组
    app.globalData.orderList = orderList
    wx.navigateTo({
      url: '/pages/order/order?price=' + this.data.goods.price * 100,
    })
  },
  //跳转到购物车界面
  toCart() {
    this.updateActive(2) //真的关键！这里是为了处理tabbar下标显示异常的问题，这里是因为数据在store中进行了动态绑定最后用相同的方法成功改正
    wx.switchTab({
      url: '../../pages/cart/cart',
    })
  },
  onShareAppMessage(res){
    let myObj = {
      title:'琪琪的手工饰品屋',
      path:"/pages/goodsDetail/goodsDetail",
    }
    return myObj;
  },
  watchValue() {
    wx.showLoading({
      title: '加载中',
    })
    // 定期检查flag的值
    var intervalId = setInterval(function () {
      if (flag === 2) {
        console.log('flag值更改为2')
        wx.hideLoading()
        // 在需要时关闭定时器
        clearInterval(intervalId)
      }
    })
  }
})